<template>
  <div class="main-box">
    <el-form ref="formRef" :model="formModel" :rules="rules" label-width="145px" class="dialog-form" label-position="right" status-icon>
      <el-form-item label="所属城市:" prop="cityCode">
        <query-dict
          :dict-list="cityList"
          class="form-select"
          :disabled="initCityCode !== '00'"
          placeholder="请选择所属城市"
          :value.sync="formModel.cityCode"
          @changeValue="changeCity"
        ></query-dict>
      </el-form-item>
      <el-form-item label="所属区域:" v-if="areaList.length">
        <query-dict
          :dict-list="areaList"
          class="form-select"
          :disabled="!formModel.cityCode"
          placeholder="请选择所属区域"
          :value.sync="formModel.areaCode"
          @changeValue="changeArea"
        ></query-dict>
      </el-form-item>
      <el-form-item label="网点名称:" prop="parkName">
        <el-input v-model.trim="formModel.parkName" class="form-item" placeholder="请输入网点名称" clearable />
      </el-form-item>
      <el-form-item label="网点详细地址:" prop="parkAddress">
        <el-input type="textarea" v-model.trim="formModel.parkAddress" class="form-item" placeholder="请输入责任人" clearable />
      </el-form-item>
      <el-form-item label="经度:" prop="longitude">
        <el-input v-model.trim="formModel.longitude" class="form-item" placeholder="请输入经度" clearable />
      </el-form-item>
      <el-form-item label="纬度:" prop="latitude">
        <el-input v-model.trim="formModel.latitude" class="form-item" placeholder="请输入纬度" clearable />
      </el-form-item>
      <el-form-item label="还车距离:" prop="returnDistance">
        <el-input v-model.trim="formModel.returnDistance" type="number" class="form-item" placeholder="请输入还车距离" clearable>
          <template slot="append">米</template>
        </el-input>
      </el-form-item>

      <el-form-item label="网点类型:" prop="isCooperation">
        <query-dict
          :dict-list="cooperationTypeList"
          class="form-select"
          filterable
          placeholder="请选择网点类型"
          :value.sync="formModel.isCooperation"
        ></query-dict>
      </el-form-item>
      <el-form-item label="责任人:" prop="dutyPerson">
        <el-input v-model.trim="formModel.dutyPerson" class="form-item" placeholder="请输入责任人" clearable />
      </el-form-item>
      <el-form-item label="网点状态:" prop="isTemporary">
        <query-dict :dict-list="disabledStatus" class="form-select" placeholder="请选择网点状态" :value.sync="formModel.isTemporary"></query-dict>
      </el-form-item>
      <el-form-item label="网点描述:">
        <el-input type="textarea" v-model.trim="formModel.remark" class="form-item" placeholder="请输入网点信息描述" clearable />
      </el-form-item>
      <el-form-item label="网点车位数:" prop="spaceNums">
        <el-input v-model.trim="formModel.spaceNums" class="form-item" placeholder="请输入车位数" clearable />
      </el-form-item>
      <el-form-item label="停车场类型:" prop="parkType">
        <query-dict :dict-list="typeList" filterable class="form-select" placeholder="请选择停车类型" :value.sync="formModel.parkType"></query-dict>
      </el-form-item>
      <el-form-item label="停车场费用(小时/元):">
        <el-input v-model.trim="formModel.parkMoney" class="form-item" placeholder="请输入停车场费用" clearable />
      </el-form-item>
      <el-form-item label="停车场费用(天/元):">
        <el-input v-model.trim="formModel.parkDayMoney" class="form-item" placeholder="请输入停车场费用" clearable />
      </el-form-item>
    </el-form>
    <div class="amap-page-container">
      <div class="msgTip">搜索网点名称，填充网点经纬度相关信息</div>
      <el-amap-search-box class="search-box" :search-option="searchOption" :on-search-result="onSearchResult"></el-amap-search-box>
      <el-amap class="amap-box" :zoom="zoom" :center="center" :events="events" :plugin="plugin" pitch-enable="false">
        <el-amap-marker
          v-for="marker in markers"
          :position="marker.position"
          :key="marker.id"
          :events="marker.events"
          :icon="marker.icon"
        ></el-amap-marker>
        <el-amap-info-window
          v-if="window"
          :position="window.position"
          :visible="window.visible"
          :content="window.content"
          :offset="window.offset"
          :close-when-click-map="true"
          :is-custom="true"
        >
          <div class="info-window">{{ window.name }}</div>
        </el-amap-info-window>
      </el-amap>
    </div>
  </div>
</template>

<script>
import utils from 'utils'
import dictObj from '@/store/dictData'
import MixinForm from 'mixins/form'

export default {
  mixins: [MixinForm],
  props: {
    initData: {
      type: Object,
      default() {
        return {
          parkName: '',
          dutyPerson: '',
          cityCode: '',
          areaCode: '',
          parkAddress: '',
          latitude: '',
          longitude: '',
          isCooperation: '',
          spaceNums: '',
          parkType: '',
          parkMoney: '',
          parkDayMoney: '',
          isTemporary: 1,
          returnDistance: 100,
          remark: ''
        }
      }
    },
    typeList: {
      type: Array,
      default() {
        return []
      }
    },
    isEdit: {
      type: Boolean,
      default: false
    }
  },
  data(vm) {
    return {
      initCityCode: '',
      cooperationTypeList: dictObj.cooperationTypeList,
      disabledStatus: dictObj.disabledStatus,
      rules: {
        parkName: [{ required: true, message: '请输入网点名称', trigger: 'blur' }],
        dutyPerson: [{ required: true, message: '请输入网点责任人', trigger: 'blur' }],
        cityCode: [{ required: true, message: '请选择城市', trigger: 'change' }],
        parkAddress: [{ required: true, message: '请输入网点详细地址', trigger: 'blur' }],
        longitude: [{ required: true, message: '请输入网点经度', trigger: 'blur' }],
        latitude: [{ required: true, message: '请输入网点纬度', trigger: 'blur' }],
        isCooperation: [{ required: true, message: '请选择网点类型', trigger: 'blur' }],
        spaceNums: [{ required: true, message: '请输入网点车位数', trigger: 'blur' }],
        parkType: [{ required: true, message: '请选择停车场类型', trigger: 'change' }],
        isTemporary: [{ required: true, message: '请选择网点状态', trigger: 'change' }],
        returnDistance: [{ required: true, message: '请输入还车距离', trigger: 'blur' }]
      },
      searchOption: {
        city: '广东省',
        citylimit: true
      },
      cityList: [], // 市集合
      areaList: [], //区集合
      posResult: [],
      markers: [],
      windows: [], // 地图弹框信息集合
      window: '', // 当前车弹框信息
      center: [114.124592, 22.648286],
      zoom: 16, // 地图放大倍数
      events: {
        click(e) {
          const { lng, lat } = e.lnglat
          vm.markers = [
            {
              position: [lng, lat]
            }
          ]

          // 这里通过高德 SDK 完成。
          const geocoder = new AMap.Geocoder({
            radius: 1,
            extensions: 'all'
          })
          geocoder.getAddress([lng, lat], (status, result) => {
            if (status === 'complete' && result.info === 'OK') {
              if (result && result.regeocode) {
                const { formattedAddress, pois } = result.regeocode
                console.log(result.regeocode, lng, lat)
                vm.formModel = {
                  ...vm.formModel,
                  parkAddress: formattedAddress,
                  latitude: lat,
                  longitude: lng,
                  parkName: pois.length ? pois[0].name : ''
                }
                vm.$nextTick()
              }
            }
          })
        }
      },
      plugin: [
        'ToolBar',
        'Scale'
        // {
        //   pName: 'Geolocation',
        //   events: {
        //     init() {},
        //     complete: result => {
        //       console.log(result)
        //       //定位成功
        //       // var address = result.formattedAddress
        //       // var point = result.position
        //       // var obj = {
        //       //   address: address,
        //       //   name: '',
        //       //   location: point
        //       // }
        //       // vm.list = [obj]
        //       // vm.makerConf.position = [point.lng, point.lat]
        //     },
        //     error: err => {
        //       console.log(err)
        //     }
        //   }
        // }
      ]
    }
  },
  computed: {
    formModel: {
      get() {
        return this.initData
      },
      set(val) {
        this.$emit('update:init-data', val)
      }
    }
  },
  created() {
    const { cityCode, cityName, latitude, longitude, companyId } = utils.getStore('cityInfo')
    if (cityCode === '00') {
      this.searchOption.citylimit = false
      this.initCityCode = '00'
    } else {
      this.cityList = [
        {
          label: cityName,
          value: cityCode
        }
      ]
      this.center = [longitude, latitude]
      this.formModel.cityCode = cityCode
      this.searchOption.city = cityName
      this.initCityCode = '11'
    }
    if (this.isEdit) {
      const { latitude, longitude, parkAddress, parkName, ...other } = this.initData
      this.center = [longitude, latitude]
      this.posResult = [{ ...other, lat: latitude, lng: longitude, address: parkAddress, name: parkName }]
    }
    this.formModel.companyId = companyId
    this.getCityArea(cityCode)
  },
  methods: {
    onSearchResult(pois) {
      console.log(pois)
      this.posResult = pois
      // let latSum = 0
      // let lngSum = 0
      if (pois.length > 0) {
        let center = {
          lng: pois[0].lng,
          lat: pois[0].lat
        }
        // pois.forEach(poi => {
        //   let { lng, lat } = poi
        //   lngSum += lng
        //   latSum += lat
        // })
        // let center = {
        //   lng: lngSum / pois.length,
        //   lat: latSum / pois.length
        // }
        this.center = [center.lng, center.lat]
      }
    },
    // cityCode为00时，获取全国城市列表；根据城市code查询地域信息
    getCityArea(cityCode) {
      if (cityCode === '00') {
        const cityList = utils.getStore('cityList')
        this.cityList = this.$store.getters.allCity.length ? this.$store.getters.allCity : cityList
      } else {
        this.$api.settings.fetch('queryCityAreaByCode', { cityCode }).then(res => {
          const curList = res.map(val => ({
            label: val.name,
            value: val.code,
            longitude: val.longitude,
            latitude: val.latitude
          }))
          this.areaList = curList
        })
      }
    },
    changeCity(item) {
      this.formModel.areaCode = ''
      this.areaList = []
      if (item && item.value) {
        this.getCityArea(item.value)
      }
    },
    changeArea(item) {
      this.formModel.areaName = item.label
    }
  },
  watch: {
    posResult(newVal) {
      if (newVal) {
        const markers = []
        const windows = []
        const that = this
        newVal.forEach((item, index) => {
          markers.push({
            position: [item.lng, item.lat],
            events: {
              click() {
                that.formModel = {
                  ...that.formModel,
                  parkAddress: item.address,
                  latitude: item.lat,
                  longitude: item.lng,
                  parkName: item.name
                }
              },
              mouseover() {
                that.windows.forEach(window => {
                  window.visible = false // 关闭窗体
                })
                that.window = that.windows[index]
                that.$nextTick(() => {
                  that.window.visible = true
                })
              }
            }
          })
          windows.push({
            position: [item.lng, item.lat],
            isCustom: true,
            offset: [-2, -40], // 窗体偏移
            showShadow: false,
            visible: false, // 初始是否显示,
            name: item.name
          })
        })
        this.markers = markers
        this.windows = windows
      } else {
        this.markers = []
        this.windows = []
      }
    }
  }
}
</script>
<style lang="less" scoped>
.main-box {
  display: flex;
}
.dialog-form {
  flex: 2;
}
.amap-page-container {
  position: relative;
  flex: 3;
  max-height: 500px;
  margin: 0 10px;
  .msgTip {
    font-size: @f14;
    line-height: 30px;
    color: @danger;
  }
}
.search-box {
  position: absolute !important;
  top: 30px;
  right: 20px;
  z-index: 1;
  padding: 0 20px;
  margin-top: 10px;
  color: @active;
  border: 1px solid @border-default;
  border-radius: 10px;
}
.info-window {
  display: flex;
  flex-direction: column;
  justify-content: center;
  min-width: 100px;
  min-height: 40px;
  padding: 10px 5px;
  text-align: center;
  background-color: @white;
  border: 1px solid @primary-color;
  border-radius: 8px;
  &::before {
    position: absolute;
    bottom: -12px;
    left: 43%;
    width: 0;
    height: 0;
    content: '';
    border: 10px solid;
    border-color: @primary-color transparent transparent;
  }
  &::after {
    position: absolute;
    bottom: -10px;
    left: 43%;
    width: 0;
    height: 0;
    content: '';
    border: 10px solid;
    border-color: @white transparent transparent;
  }
}
</style>
